package com.test.first;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Main5Activity extends AppCompatActivity implements Runnable{


    EditText rmb;
    TextView result;

    private String updateDate = "";
    private float dollarRate = 0.1503f;
    private float euroRate = 0.1266f;
    private float wonRate = 170.2708f;
    private static final String TAG = "Main5Activity";
    Handler handler;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main5);
        rmb = findViewById(R.id.input_rmb);
        result = findViewById(R.id.result);



        SharedPreferences sharedPreferences = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        PreferenceManager.getDefaultSharedPreferences(this);

        dollarRate = sharedPreferences.getFloat("dollar_rate",0.0f);
        euroRate = sharedPreferences.getFloat("euro_rate",0.0f);
        wonRate = sharedPreferences.getFloat("won_rate",0.0f);
        updateDate = sharedPreferences.getString("update_date","");


        Date today = Calendar.getInstance().getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String todayStr = sdf.format(today);


        Log.i(TAG,"onCreate: sp updateDate=" + updateDate);
        Log.i(TAG,"onCreate: todayStr=" + todayStr);
        Thread t = new Thread(this);
        t.start();
        if(!todayStr.equals(updateDate)){
            Log.i(TAG,"需要更新" );

        }else{
            Log.i(TAG,"不需要更新");
        }


        handler = new Handler(Looper.myLooper()){
            @Override
            public void handleMessage(@NonNull Message msg) {

                if(msg.what == 6){
                    Bundle bdl = (Bundle)msg.obj;
//                    Log.i(TAG,"handlerMessage: str=" + str);
//                    result.setText(str);

                    dollarRate = bdl.getFloat("dollar-rate");
                    euroRate = bdl.getFloat("euro-rate");
                    wonRate = bdl.getFloat("won-rate");


                    SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sp.edit();
                    editor.putFloat("dollar_rate",dollarRate);
                    editor.putFloat("euro_rate",euroRate);
                    editor.putFloat("won_rate",wonRate);
                   // editor.putString("update_date",todayStr);
                    editor.apply();


                    Toast.makeText(Main5Activity.this,"汇率已更新",Toast.LENGTH_SHORT).show();
                }

                super.handleMessage(msg);
            }
        };


    }


    public void click(View btn){

        String str =rmb.getText().toString();
        if(str!=null&&str.length()>0){

            float r = 0.1f;

            if(btn.getId()==R.id.btn_dollar){
                r=dollarRate;

            }else if(btn.getId()==R.id.btn_euro){
                r=euroRate;
            }else{
                r=wonRate;
            }

            r=r*Float.parseFloat(str);
            result.setText(String.valueOf(r));

        }else{


            Toast.makeText(this, "请输入计算的金额", Toast.LENGTH_SHORT).show();
        }

    }

    public void openConfig(View btn){
        Log.i(TAG,"openConfig:");

        Intent conf = new Intent(this,ConfigActivity.class);
        conf.putExtra("dollar_key",dollarRate);
        conf.putExtra("euro_key",euroRate);
        conf.putExtra("won_key",wonRate);

        Log.i(TAG,"openconfig:dollarRate=" + dollarRate);
        Log.i(TAG,"openconfig:euroRate=" + euroRate);
        Log.i(TAG,"openconfig:wonRate=" + wonRate);


//        startActivity(conf);
        startActivityForResult(conf,6);

    }
    @Override
    public void run() {
        Log.i(TAG,"run:.........");
//        URL url = null;
//        try{
//            url = new URL("http://www.usd-cny.com/bankofchina.htm");
//            HttpURLConnection http = (HttpURLConnection)url.openConnection();
//            InputStream in = http.getInputStream();
//            String html = inputStream2String(in);
//            Log.i(TAG,"run: html=" + html);
//
//        }catch (MalformedURLException e){
//            e.printStackTrace();
//            Log.e(TAG,"run: ex=" + e.toString());
//
//        }catch (IOException e){
//            e.printStackTrace();
//            Log.e(TAG,"run: ex=" + e.toString());
//        }
        SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        Bundle bundle = new Bundle();
        try {

            Document doc = Jsoup.connect("http://www.usd-cny.com/icbc.htm").get();
            Log.i(TAG, "run: title=" + doc.title());
//            Elements tables = doc.getElementsByTag("table");
//            Element table1 = tables.first();

            Element table = doc.getElementsByTag("table").first();
            Elements trs = table.getElementsByTag("tr");
            for(Element tr : trs){
                Elements tds = tr.getElementsByTag("td");

                if(tds.size()>0){
                    String str = tds.get(0).text();
                    String val = tds.get(4).text();
                    Log.i(TAG,"run: " + str +"=>"+val);
                    if("美元".equals(str)){
                        float r = 100/Float.parseFloat(val);
                        Log.i(TAG, "meiyuan:"+r);
                        dollarRate=r;
                        editor.putFloat("dollar_rate",dollarRate);
                    }else if("欧元".equals(str)){
                        float r = 100/Float.parseFloat(val);
                        euroRate=r;
                        editor.putFloat("euro_rate",euroRate);
                        Log.i(TAG, "Ouyuan="+euroRate);
                    }else if("韩元".equals(str)){
                        float r = 100/Float.parseFloat(val);
                        wonRate=r;
                        editor.putFloat("won_rate",wonRate);
                    }
                    editor.apply();
                }
            }

//            Element e1 = doc.select("body > section > div > div > article > table > tbody > tr:nth-child(8) > td:nth-child(6)").first();
//            Log.i(TAG,"欧元=" + e1.text());
//            Element e2 = doc.select("body > section > div > div > article > table > tbody > tr:nth-child(27) > td:nth-child(6)").first();
//            Log.i(TAG,"美元=" + e2.text());
//            Element e3 = doc.select("body > section > div > div > article > table > tbody > tr:nth-child(14) > td:nth-child(6)").first();
//            Log.i(TAG,"韩元=" + e3.text());
//            editor.putFloat("dollar_rate",Float.parseFloat(e2.text()));
//            dollarRate=Float.parseFloat(e2.text());
//            editor.putFloat("euro_rate",Float.parseFloat(e1.text()));
//            euroRate=Float.parseFloat(e1.text());
//            editor.putFloat("won_rate",Float.parseFloat(e3.text()));
//            wonRate=Float.parseFloat(e3.text());
//            Log.i(TAG, "new Rate="+wonRate);
//            editor.apply();
//            Element table1 =doc.getElementsByTag("table").first();
//            Elements tds = table1.getElementsByTag("td");
//
//            for(Element td :tds){
//                Log.i(TAG,"run: td=" +  td);
//                Log.i(TAG,"run: td.next" +  td.text());
//                Log.i(TAG,"run: td.html" +  td.html());
//
//            }



//              Elements class1 = table1.getElementsByClass("bz");
//              for(Element td : class1){
//                  Log.i(TAG,"run: td=" + td);
//              }


        }catch(IOException e){
            e.printStackTrace();
            Log.i(TAG, "run: title=" + e.toString());
        }


        Message msg = handler.obtainMessage(6,bundle);

        handler.sendMessage(msg);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode==6&& resultCode==2){

            Bundle bundle = data.getExtras();
            dollarRate = bundle.getFloat("key_dollar",0.0f);
            euroRate = bundle.getFloat("key_euro",0.0f);
            wonRate = bundle.getFloat("key_won",0.0f);
            Log.i(TAG,"onActivityResult: dollarRate=" +dollarRate);
            Log.i(TAG,"onActivityResult: euroRate=" +euroRate);
            Log.i(TAG,"onActivityResult: wonRate=" +wonRate);


        }

        super.onActivityResult(requestCode, resultCode, data);


        SharedPreferences sp = getSharedPreferences("myrate", Activity.MODE_PRIVATE);

        SharedPreferences.Editor editor = sp.edit();
        editor.putFloat("dollar_rate",dollarRate);
        editor.putFloat("euro_rate",euroRate);
        editor.putFloat("won_rate",wonRate);
        editor.apply();
    }




    private String inputStream2String(InputStream inputStream) throws  IOException{
        final int bufferSize = 1024;
        final char[] buffer = new char[bufferSize];
        final StringBuilder out = new StringBuilder();
        Reader in = new InputStreamReader(inputStream,"gb2312");
        while(true){
            int rsz = in.read(buffer,0,buffer.length);
            if(rsz<0)
                break;
            out.append(buffer,0,rsz);
        }
        return out.toString();
    }

}